import Vue from 'vue'
import router from '../router'
import { AjaxPlugin } from 'vux'
Vue.use(AjaxPlugin)

// 设置请求地址
Vue.prototype.$http.defaults.baseURL = process.env.API_ROOT + '/frontend'
// console.log(process.env.API_ROOT)
// 设置超时时间
Vue.prototype.$http.defaults.timeout = 20000
// http request 请求拦截器，axios请求时如果有token则携带token
Vue.prototype.$http.interceptors.request.use(
  config => {
    // let token = '4vQesWxvSf6TBkIq'
    // sessionStorage.setItem('token', token)
    let token = sessionStorage.getItem('token')
    if (token) {
      config.headers.token = token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// http response 服务器响应拦截器
Vue.prototype.$http.interceptors.response.use(
  response => {
    let {code, data, msg} = response.data;
    if (code == 500) {
      if (msg === '未登录') {
        Vue.$vux.alert.show({
          title: '提示',
          content: msg,
          hideOnBlur: true,
          onHide() {
            localStorage.removeItem('token');
            router.replace({
              path: '/login'
            });
          }
        });
      } else {
        Vue.$vux.alert.show({
          title: '提示',
          content: msg,
          hideOnBlur: true
        });
        // Vue.$message.error(msg);
      }
    }
    return response;
  },
  error => {
    console.log(error)
    // 请求超时处理
    var originalRequest = error.config
    console.log(error.code, error.message, originalRequest)
    if (error.message == 'Network Error' || (error.code == 'ECONNABORTED' && error.message.indexOf('timeout') != -1 && !originalRequest._retry)) {
        // console.log(error.config);
      router.push({
        path: '/requestError'
      })
      return Promise.reject(error)
    }
    if (error.response) {
      switch (error.response.status) {
        case 404:// 404状态，跳转到404处理页面
          router.push({
            path: '/requestError'
          })
          break
      }
    }
    return Promise.reject(error)
    // return Promise.reject(error.response)
  })
